//
//  UIImage+Color.m
//  JPProjectConfigureDemo
//
//  Created by Carpenter on 2018/2/6.
//  Copyright © 2018年 carpenter. All rights reserved.
//

#import "UIImage+Color.h"

@implementation UIImage (Color)


+(UIImage *)jp_imageWithColor:(UIColor *)color{
    return [self jp_imageWithColor:color size:CGSizeMake(1, 1)];
}
+(UIImage *)jp_imageWithColor:(UIColor *)color size:(CGSize)size{
    return [self jp_imageWithColor:color size:size radius:0];
}
+ (UIImage *)jp_imageWithColor:(UIColor *)color size:(CGSize)size radius:(CGFloat)radius{
    return [self jp_imageWithColor:color size:size radius:radius borderColor:nil borderWidth:0.0];
}
+ (UIImage *)jp_imageWithColor:(UIColor *)color size:(CGSize)size radius:(CGFloat)radius borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth{
    
    UIGraphicsBeginImageContextWithOptions(size, radius == 0, [UIScreen mainScreen].scale);
    
    borderColor = borderColor?:[UIColor clearColor];
    
    CGRect targetRect = (CGRect){0, 0, size.width, size.height};
    UIImage *finalImage = nil;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    if (radius == 0) {
        if (borderWidth > 0) {
            CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
            CGContextSetLineWidth(context, borderWidth);
            CGContextFillRect(context, targetRect);
            
            targetRect = CGRectMake(borderWidth / 2, borderWidth / 2, size.width - borderWidth, size.height - borderWidth);
            CGContextStrokeRect(context, targetRect);
        } else {
            CGContextFillRect(context, targetRect);
        }
    } else {
        targetRect = CGRectMake(borderWidth / 2, borderWidth / 2, size.width - borderWidth, size.height - borderWidth);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:targetRect
                                                   byRoundingCorners:UIRectCornerAllCorners
                                                         cornerRadii:CGSizeMake(radius, radius)];
        CGContextAddPath(UIGraphicsGetCurrentContext(), path.CGPath);
        
        if (borderWidth > 0 && borderColor) {
            CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
            CGContextSetLineWidth(context, borderWidth);
            CGContextDrawPath(context, kCGPathFillStroke);
        } else {
            CGContextDrawPath(context, kCGPathFill);
        }
    }
    
    finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return finalImage;
    
}

@end


